/***************************************************************************//**
 * @file     bl_message.h
 * @brief    This file is the header file for messages.
 * @version  V1.0.0
 * @date     May-2021
 * @author   Zhixin Semiconductor
 *
 * @note
 * Copyright (C) 2021 Zhixin Semiconductor Ltd. All rights reserved.
 *
 ******************************************************************************/
#ifndef BL_MESSAGE_H
#define BL_MESSAGE_H



#ifdef Z20K11X_SDK
#include "Z20K11xM_can.h"
#else
#include "can_drv.h"
#endif

#define MESSAGE_BUF_LEN   64U

#define MES_ID_HOST_CONNECT     0xFFU
#define MES_ID_HOST_RECORD      0xF1U
#define MES_ID_HOST_RECORD_END  0xF2U
#define MES_ID_HOST_FILE_END    0xFEU

#define MES_ID_BL_READY         0xD1U
#define MES_ID_BL_BUSY          0xD2U
#define MES_ID_BL_UPGRADE_END   0xD3U
#define MES_ID_BL_ERROR         0xD4U

#define MES_LEN_NORMAL          2U
#define MES_LEN_ERR             3U
#define MES_LEN_UPG_END         3U

#define MES_RECORD_MAX_LEN      128U

#define MES_RECORD_HEADER_LEN   3U
#define MES_RECORD_FLAG         0x52U

#define MES_RECORD_CHECKSUM_LEN        1U
#define MES_RECORD_ADDR_LEN            4U

#define MES_RECORD_ID_INFO      0U
#define MES_RECORD_ID_DATA      1U
#define MES_RECORD_ID_ENTRY     2U

#define MES_ALLOWED_REC_INFO       0x01U
#define MES_ALLOWED_REC_DATA       0x02U
#define MES_ALLOWED_REC_ENTRY      0x04U

#define MES_UPGRADE_STA_SUCC    0U
#define MES_UPGRADE_STA_FAIL    1U

#define MES_ERR_FLASH               0x01U
#define MES_ERR_MES                 0x02U
#define MES_ERR_RECORD_LEN          0x03U
#define MES_ERR_RECORD_INDEX        0x04U
#define MES_ERR_RECORD_FLAG         0x05U
#define MES_ERR_VERSION_LOW         0x06U
#define MES_ERR_RECORD_CHECKSUM     0x07U
#define MES_ERR_RECORD_ID           0x08U
#define MES_ERR_ADDR                0x09U
#define MES_ERR_UNEXP_REC_ID        0x0AU
#define MES_ERR_SRAM                0x0BU
#define MES_ERR_FLASH_DRV_INVALID   0x0CU

#define MES_SetAllowedRecId(id)      mesAllowedId = (id)

extern uint32_t mesAllowedId;

typedef struct
{
    uint32_t len;
    uint8_t data[MESSAGE_BUF_LEN];
}MessageBuf_t;

typedef struct
{
    uint32_t index;    
    uint8_t data[MES_RECORD_MAX_LEN];
    uint8_t expectedMesIndex;
    uint8_t expectedSubIndex;
}MessageRecord_t;

void MessageInit(void);
FlagStatus_t MessageReadOneFrame(MessageBuf_t *buf);
void MessageProcess(MessageBuf_t *buf);
void MessageTransmit(uint8_t *data, uint8_t len);
void MessageTransmitErrMes(uint8_t rcvId, uint8_t errId);
FlagStatus_t MessageCheckRecIdAllowedStatus(uint32_t status);

#endif /* __BL_MESSAGE_H */